<!-- 地图区域树 -->

<template>
  <div :class="className">
    <div class="inFlexCC" @click.stop="MAP.fold = !MAP.fold">
      <i class="el-icon-s-grid" />
    </div>

    <EasyTree :tree="treeData" height="calc(100% - 60px)">
      <template #default="{ data, nodeClass }">
        <div :class="nodeClass">
          <el-checkbox v-if="data.device" v-bind="getProps(data)" @change="(value) => toChoose(value, data.device)">
            <CommonSvg :src="CORE.imageIOT(data.device)" />
            <span>{{ data.name }}</span>
          </el-checkbox>
          <span v-else>{{ data.name }}</span>
        </div>
      </template>

      <template #bottom>
        <BtnDefault title="清空" :disabled="!MAP.chosenList.length" @click="MAP.chosenList = []" />
        <BtnPrimary title="播放" :disabled="!MAP.chosenList.length" @click="device_openShow" />
      </template>
    </EasyTree>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

const transTree = (tree, select) => {
  return tree.map((node) => {
    const deviceList = select.filter((item) => item.areaId === node.id)
      .map((item) => ({ children: [], id: item.id, name: item.deviceName, device: item }))
    const children = [...deviceList, ...node.children]
    return { ...node, children }
  })
}

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MapTree',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [
    CORE.mixBase(),
    CORE.mixInfo('map', 'map_'),
    CORE.mixList('map', 'map_'),
    CORE.mixSelect('device', 'device_'),
    CORE.mixModal('device', 'device_'),
  ],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 样式类
     */
    className() {
      const name = 'SecureOverview-MapTree'
      const foldStr = this.MAP.fold ? ` ${name}-folded` : ''
      return `${name}${foldStr}`
    },

    /**
     * 区域树数据
     */
    treeData() {
      const { MAP: { activeTab }, device_select } = this
      const tree = [CORE.REGION.MY_MAP[activeTab]]
      return transTree(tree, device_select)[0].children
    },
  },

  /**
   * 创建完成 (先抽取再调用)
   */
  created() {
    this.MAP.chosenList = []
    this.MAP.fold = true
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 获取属性
     */
    getProps({ device }) {
      const { MAP: { chosenList } } = this
      const value = chosenList.some(item => item.id === device.id)
      const disabled = !device.thirdCode || chosenList.length >= 25
      return { value, disabled }
    },

    /**
     * 切换选中
     */
    toChoose(value, device) {
      const { MAP: { chosenList } } = this
      if (value) chosenList.push(device)
      else {
        const index = chosenList.findIndex(item => item.id === device.id)
        if (index >= -1) chosenList.splice(index, 1)
      }
    },
  },
}
</script>

<style lang="scss">
@import './index.scss';
</style>
